#include <string.h>
#include <iostream>
using std::cout;
using std::ostream;
using std::endl;
//回顾一下深拷贝的string的原理
class String{
public:
    String()
    :_pstr(new char[1]())
    {

    }
    String(const char * pstr)
    :_pstr(new char[strlen(pstr) + 1]())
    {
        strcpy(_pstr, pstr);
    }
    String(const String & rhs)
    :_pstr(new char[strlen(rhs._pstr) + 1]())
    {
        strcpy(_pstr, rhs._pstr);
    }
    String & operator=(const String & rhs){
        if(this != &rhs){
            delete [] _pstr;
            _pstr = new char[strlen(rhs._pstr) + 1]();
            strcpy(_pstr, rhs._pstr);
        }
        return *this;
    }
    ~String(){
        if(_pstr){
            delete [] _pstr;
            _pstr = nullptr;
        }
    }
    friend ostream & operator<<(ostream & os, const String & rhs);

private:
    char * _pstr;
};
ostream & operator<<(ostream & os, const String & rhs){
    if(rhs._pstr){
        os << rhs._pstr;
    }
    return os;
}

void test(){
    String s;
    String s2("hello");
    cout << s2 << endl;
    String s3 = s2;
    cout << s3 << endl;
    String s4("world");
    cout << s4 << endl;
    s3 = s4;
    cout << s3 << endl;
}
//test2里面拷贝构造函数和赋值运算符的处理的右操作数不太一样
//问题：尝试写出此时代码对应的内存图示
void test2(){
    String s = String("hello");
    cout << s << endl;
    String s2("hello,python");
    s2 = String("hello,c++");
    cout << s2 << endl;
}

void test3(){
    int a = 1, b = 2;
	&a;
	&b;
	&(a + b);//error,右值，临时值，无法取地址操作
	&10;//error,右值，无法取地址操作
	&String("hello");//error,右值，无法取地址操作

    //非const引用尝试绑定
	int & r1 = a;
	int & r2 = 1;//error,非const引用无法绑定右值

    //const引用尝试绑定
	const int & r3 = 1;
	const int & r4 = a;

	String s1("hello");
	String s2("wangdao");
	&s1;
	&s2;
	&(s1 + s2);//error,无法对右值进行取地址
}

int main()
{
    test2();
    return 0;
}

